/**
 * 
 */
package org.cuatrovientos.erp.dao;

import java.util.List;

import org.cuatrovientos.erp.model.Delegation;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 
 *
 */
public class DelegationDAO implements DelegationDAOInterface {

	@Autowired
	 private SessionFactory sessionFactory;
	

	/**
	 * default constructor
	 */
	public DelegationDAO () {
		
	}
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	
	/* 
	 * selects one delegation by Id
	 * @param id
	 * @return delegation
	 */
	 @Transactional(readOnly = true)
	public Delegation selectById(int id) {
		 Delegation delegation = (Delegation) getSession().get(Delegation.class, id);
	    return delegation;
	}

	/*
	 * retrieves all delegations from db
	 * @return List of delegations
	 */
	 @Transactional(readOnly = true)
	public List<Delegation> selectAll() {
	 
	    List<Delegation> delegations = getSession().createQuery("from delegation").list();
	    return delegations;
	}
	
	/*
	 * retrieves all delegation from db
	 * @return List of delegation
	 */
	 @Transactional(readOnly = true)
	public int selectAllCount() {
	    List<Delegation> delegations = getSession().createQuery("from delegation").list();
	    return delegations.size();
	}

	/*
	 * inserts a new delegation in database
	 * retrieves generated id and sets to delegation instance
	 * @param new delegation
	 */
	 @Transactional
	public void insert(Delegation delegation) {
	    Integer id = (Integer) getSession().save(delegation);
	    delegation.setId(id);           
	}

	/*
	 * updates delegation
	 * @param delegation to update
	 */
	 @Transactional
	public void update(Delegation delegation) {
		getSession().merge(delegation);
	}

	/*
	 * delete given delegation
	 * @param delegation to delete
	 */
	 @Transactional
	public void delete(Delegation delegation) {
		getSession().delete(delegation);
	}

	 @Transactional
	public void saveOrUpdate(Delegation delegation) {

		getSession().saveOrUpdate(delegation);
		
	}

	 /**
	  * deletes using id
	  */
	 @Transactional
	public void deleteById(int id) {
		 Delegation delegation = (Delegation) getSession().load(Delegation.class,id);
		 getSession().delete(delegation);
	}

	 /**
	  * performs search operation
	  */
	 @Transactional(readOnly = true)
	public List<Delegation> search(String name) {
		   Query query = getSession().createQuery("from delegation d where d.name like :name");
          query.setParameter("name", "%"+name+"%");
          
          List<Delegation> delegations = query.list();
		
          return delegations;
	}
}
